const fs = require('fs')
const path = require('path')
const qr = require('qr-image')
const express = require('express')
const app = express()

app.set('views', path.join(__dirname, 'views'))
app.engine('.html', require('ejs').__express)
app.set('view engine', 'html')

app.use(express.static(path.join(__dirname, 'public')))

const conf = require('./conf')
const port = conf.port
const user = conf.user

for (let i = 0; i < user.length; i++) {
    const u = user[i]
    u.me = qr.imageSync(u.me, { size: 10 }).toString('base64')
    u.wx = qr.imageSync(u.wx, { size: 10 }).toString('base64')
    u.qq = qr.imageSync(u.qq, { size: 10 }).toString('base64')

    app.get(u.ph, function(req, res, nex) {
        let UA = req.headers['user-agent']
        console.log(req.path, UA)
        if (UA.indexOf(' Alipay') !== -1) {
            res.redirect(301, u.ap)
        } else if (UA.indexOf(' MicroMessenger') !== -1) {
            // res.render('index', { t: u.nm, pay: u.wx, msg: '长按"识别图片中的二维码"向我付款' })
            res.redirect(301, u.wx)
        } else if (UA.indexOf(' QQ/') !== -1) {
            res.render('index', { t: u.nm, pay: u.qq, msg: '长按图片"扫描二维码"向我付款' })
        } else {
            res.render('index', { t: u.nm, pay: u.me, msg: '请使用微信/支付宝/QQ扫码付款' })
        }
    })
}

app.use(function(req, res, next) {
    res.status(404).send('404 is Fuck')
})

app.use(function(err, req, res, next) {
    console.log(err.stack)
    res.status(500).send('500 Server Error')
})

app.listen(port)

console.log('Listening on', port)